package com.fy.utils;

/**
 *
 */

import com.alibaba.fastjson.JSON;
import com.fy.annotion.Log;
import lombok.extern.slf4j.Slf4j;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.*;
import java.util.Map.Entry;

/**
 * @author Administrator
 */
@Slf4j
public class MapUtils {

    public static HashMap<String, Object> getHashMap() {
        return new HashMap<String, Object>();
    }

    public static <T> void addToMap(Map<String, T> map, String key, T o) {
        if (o != null) {
            if (o instanceof String) {
                if (StringUtils.isEmpty((String) o)) {
                    return;
                }
            }
            map.put(key, o);
        }
    }

    public static <T> void addPercentToMap(Map<String, T> map, String key, T o) {
        addToMap(map, key, "%", o, "%");
    }

    public static void addLeftPercentToMap(Map<String, Object> map, String key, Object o) {
        addToMap(map, key, "%", o, null);
    }

    public static void addRightPercentToMap(Map<String, Object> map, String key, Object o) {
        addToMap(map, key, null, o, "%");
    }

    public static <T> void addToMap(Map<String, T> map, String key, String sBef, T o, String sAft) {
        System.out.println(key + ":" + o);
        if (o != null) {
            if (o instanceof String) {
                if (StringUtils.isEmpty((String) o)) {
                    return;
                }
            }
            if (o instanceof String && StringUtils.isEmpty(sBef) && (StringUtils.isEmpty(sAft))) {
                map.put(key, o);
            } else if (o instanceof String && !StringUtils.isEmpty(sBef) && (StringUtils.isEmpty(sAft))) {
                map.put(key, (T) (sBef + o));
            } else if (StringUtils.isEmpty(sBef) && (!StringUtils.isEmpty(sAft))) {
                map.put(key, (T) (String.valueOf(o) + sAft));
            } else if (!StringUtils.isEmpty(sBef) && (!StringUtils.isEmpty(sAft))) {
                map.put(key, (T) (sBef + String.valueOf(o) + sAft));
            }
        }
    }

    public static String addOrderByReplace(String orderby, String replace) {
        if (StringUtils.isNotEmpty(orderby)) {
            String[] list = orderby.split(" ");
            if (list.length > 0) {
                StringBuilder sb = new StringBuilder();
                if (!StringUtils.equalsIgnoreCase(list[0], replace)) {
                    list[0] = replace;
                }
                sb.append(" order by ");
                for (int i = 0; i < list.length; i++) {
                    if (i == 0) {
                        sb.append(replace);
                    } else {
                        sb.append(" ");
                        sb.append(list[i]);
                    }
                }
                return sb.toString();
            } else {
                StringBuilder sb = new StringBuilder();
                sb.append(" order by ");
                sb.append(orderby);
                return sb.toString();
            }
        } else {
            return orderby;
        }
    }

    public static String orderByReplace(String orderby, String replace) {
        if (StringUtils.isNotEmpty(orderby)) {
            StringBuilder sb = new StringBuilder();
            String[] list = orderby.split(" ");
            if (list.length > 0 && !StringUtils.endsWithIgnoreCase(list[0], replace)) {
                list[0] = replace;
                for (int i = 0; i < list.length; i++) {
                    if (i == 0) {
                        sb.append(replace);
                    } else {
                        sb.append(" ");
                        sb.append(list[i]);
                    }
                }
                return sb.toString();
            } else {
                return orderby;
            }
        } else {
            return orderby;
        }
    }

    /**
     * 将Object转换成map
     *
     * @param obj
     *
     * @return
     */
    public static Map<String, Object> bean2Map(Object obj) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if (obj != null) {
                BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                for (PropertyDescriptor property : propertyDescriptors) {
                    String key = property.getName();
                    // 过滤class属性
                    if (!key.equals("class")) {
                        // 得到property对应的getter方法
                        Method getter = property.getReadMethod();
                        Object value = getter.invoke(obj);
                        if (value != null) {
                            if (!(value instanceof String && StringUtils.isBlank((String) value))) {
                                map.put(key, value);
                            }
                        }
                    }
                }
            }
            return map;
        } catch (Exception e) {
           e.printStackTrace();

            return map;
        }
    }

    /**
     * @param obj
     *
     * @return
     */
    public static Map<String, Object> bean2MapWithEmpty(Object obj) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if (obj != null) {
                BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                for (PropertyDescriptor property : propertyDescriptors) {
                    String key = property.getName();
                    // 过滤class属性
                    if (!key.equals("class")) {
                        // 得到property对应的getter方法
                        Method getter = property.getReadMethod();
                        Object value = getter.invoke(obj);
                        if (value != null) {
                            map.put(key, value);
                        }
                    }
                }
            }
            return map;
        } catch (Exception e) {
           e.printStackTrace();

            return map;
        }
    }

    /**
     * bean转map，bean中为空的在map中也未空，但是键是有的。
     */
    public static Map<String, Object> bean2MapWithAllKey(Object obj) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if (obj != null) {
                BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                for (PropertyDescriptor property : propertyDescriptors) {
                    String key = property.getName();
                    // 过滤class属性
                    if (!key.equals("class")) {
                        // 得到property对应的getter方法
                        Method getter = property.getReadMethod();
                        Object value = getter.invoke(obj);
                        map.put(key, value);
                    }
                }
            }
            return map;
        } catch (Exception e) {
           e.printStackTrace();

            return map;
        }
    }

    /**
     * 检测一个实体bean是否存在空属性
     *
     * @param obj
     *
     * @return
     */
    public static boolean isExistNullVal(Object obj) {
        try {
            if (obj != null) {
                BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                for (PropertyDescriptor property : propertyDescriptors) {
                    String key = property.getName();
                    // 过滤class属性
                    if (!key.equals("class")) {
                        // 得到property对应的getter方法
                        Method getter = property.getReadMethod();
                        Object value = getter.invoke(obj);
                        if (value == null) {
                            return true;
                        }
                    }
                }
            }
            return false;
        } catch (Exception e) {
           e.printStackTrace();

            return false;
        }
    }

    /**
     * 将map转化为实体bean T (复杂类型)
     */
    public static <T> T map2Bean(Map<String, Object> map, Class<T> clazz) {
        if (map != null && map.size() > 0) {
            String jsonStr = JSON.toJSONString(map);
            return JSON.parseObject(jsonStr, clazz);
        }
        return null;
    }

    /**
     * @tips 将ListMap转化为实体List(复杂类型)
     */
    public static <T> List<T> map2Array(List<Map<String, Object>> listMap, Class<T> clazz) {
        if (listMap != null && listMap.size() > 0) {
            String jsonStr = JSON.toJSONString(listMap);
            return JSON.parseArray(jsonStr, clazz);
        }
        return null;
    }

    /**
     * 将map转成字符串
     *
     * @param map
     * @param splitSymbol 连接符
     *
     * @return
     *
     * @throws UnsupportedEncodingException
     */
    public static String serializeWithSplit(Map<String, Object> map, String splitSymbol)
            throws UnsupportedEncodingException {
        if (map != null) {
            // 创建一个treeMap保证key按照自然顺序进行排序
            SortedMap<String, Object> treeMap = new TreeMap<String, Object>(map);
            Set<Entry<String, Object>> set = treeMap.entrySet();
            Iterator<Entry<String, Object>> iter = set.iterator();
            String initStr = "";
            while (iter.hasNext()) {
                Entry<String, Object> entry = iter.next();
                String key = entry.getKey();
                Object val = entry.getValue();
                initStr += (key + "=" + URLEncoder.encode(val.toString(), "utf-8"))
                                   + (iter.hasNext() ? splitSymbol : "");
            }
            return initStr;
        }
        return null;
    }

    public static String serializeWithSplitUnSort(Map<String, Object> map, String splitSymbol)
            throws UnsupportedEncodingException {
        if (map != null) {
            // 创建一个treeMap保证key按照自然顺序进行排序
            Set<Entry<String, Object>> set = map.entrySet();
            Iterator<Entry<String, Object>> iter = set.iterator();
            String initStr = "";
            while (iter.hasNext()) {
                Entry<String, Object> entry = iter.next();
                String key = entry.getKey();
                Object val = entry.getValue();
                initStr += (key + "=" + val.toString())
                                   + (iter.hasNext() ? splitSymbol : "");
            }
            return initStr;
        }
        return null;
    }

    /**
     * @param map
     * @param splitSymbol
     *
     * @return
     *
     * @throws UnsupportedEncodingException
     */
    public static String serializeWithSplit(Map<String, Object> map, String splitSymbol, boolean isNeedEncode)
            throws UnsupportedEncodingException {
        if (map != null) {
            // 创建一个treeMap保证key按照自然顺序进行排序
            SortedMap<String, Object> treeMap = new TreeMap<String, Object>(map);
            Set<Entry<String, Object>> set = treeMap.entrySet();
            Iterator<Entry<String, Object>> iter = set.iterator();
            String initStr = "";
            while (iter.hasNext()) {
                Entry<String, Object> entry = iter.next();
                String key = entry.getKey();
                Object val = entry.getValue();
                if (isNeedEncode) {
                    initStr += (key + "=" + URLEncoder.encode(val.toString(), "utf-8"))
                                       + (iter.hasNext() ? splitSymbol : "");
                } else {
                    initStr += (key + "=" + val.toString()) + (iter.hasNext() ? splitSymbol : "");
                }
            }
            return initStr;
        }
        return null;
    }

}
